/*
-----------------------------------------------------------------------------
This source file is part of Labor3D
(Labor 3D Graphics Engine)

Copyright (c) 2009-2020 Rock Mao
* creator : Rock Mao
* created : 2009-5-4   14:52
* filename: LaborDynLib.cpp
-----------------------------------------------------------------------------
*/

#include "Plugin\LaborDynLib.h"
#include "Common/LaborCommonFunction.h"
NAMESPACE_LABOR3D_BEGIN

//---------------------------------------------------------------------
CLDynLib::CLDynLib(const CLString & _strName)
{
	m_strName = _strName;
	m_hInst = NULL;
}

//---------------------------------------------------------------------
CLDynLib::~CLDynLib()
{


}

//---------------------------------------------------------------------
void CLDynLib::load()
{
	// Log library load
	wprintf(L"Loading library %s\n", m_strName.c_str());
	CLString name = m_strName;
#if  LABOR_PLATFORM == LABOR_PLATFORM_LINUX
	// dlopen() does not add .so to the filename, like windows does for .dll
	if (name.substr(name.length() - 3, 3) != L".so")
		name += ".so";
#elif  LABOR_PLATFORM ==  LABOR_PLATFORM_WIN32
	if (name.substr(name.length() - 4, 4) != L".dll")
		name += L".dll";
#endif

	m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );

	if( !m_hInst )
	{
		wprintf(L"Could not load dynamic library %s\n", name.c_str());

	}
}

//---------------------------------------------------------------------
void CLDynLib::unload()
{
	// Log library unload
	printf("Unloading library  %s\n", m_strName.c_str());

	if( DYNLIB_UNLOAD( m_hInst ) )
	{
		printf("Could not unload dynamic library %s\n", m_strName.c_str());
	}
}


//-----------------------------------------------------------------------
void* CLDynLib::getSymbol( const CLString& strName ) const throw()
{
	//LPCWSTR 
	char _name[4096] = {0};
	Labor_UnicodeToLocale(strName.c_str(), _name,4096);
	return (void*)DYNLIB_GETSYM( m_hInst, _name );
}

//-----------------------------------------------------------------------
CLString CLDynLib::dynlibError( void ) 
{
//#if LABOR_PLATFORM ==  LABOR_PLATFORM_WIN32
//	LPVOID lpMsgBuf; 
//	FormatMessage( 
//		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
//		FORMAT_MESSAGE_FROM_SYSTEM | 
//		FORMAT_MESSAGE_IGNORE_INSERTS, 
//		NULL, 
//		GetLastError(), 
//		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
//		(LPTSTR) &lpMsgBuf, 
//		0, 
//		NULL 
//		); 
//	CLString ret = (char*)lpMsgBuf;
//	// Free the buffer.
//	LocalFree( lpMsgBuf );
//	return ret;
//#elif LABOR_PLATFORM == LABOR_PLATFORM_LINUX
//	return CLString(dlerror());
//#elif LABOR_PLATFORM == LABOR_PLATFORM_APPLE
//	return CLString(mac_errorBundle());
//#else
//	return CLString("");
//#endif
	return  CLString(L"");
}
NAMESPACE_LABOR3D_END